/**
 * 弹幕工具函数
 */

import type { BarrageItem, BarrageColor } from '../types'

/**
 * 预定义的弹幕颜色
 */
export const BARRAGE_COLORS: BarrageColor[] = [
  '#FFFFFF', // 纯白色
  '#FFD700', // 金黄色
  '#FF6B6B', // 珊瑚红
  '#4ECDC4', // 青绿色
  '#45B7D1', // 天蓝色
  '#96CEB4', // 薄荷绿
  '#FFEAA7', // 浅黄色
  '#DDA0DD', // 紫罗兰
  '#98D8C8', // 浅绿色
  '#F7DC6F', // 柠檬黄
  '#BB8FCE', // 淡紫色
  '#85C1E9', // 浅蓝色
  '#F8C471', // 桃色
  '#82E0AA', // 翠绿色
  '#F1948A'  // 粉红色
]

/**
 * 生成随机弹幕颜色
 */
export function getRandomColor(): BarrageColor {
  return BARRAGE_COLORS[Math.floor(Math.random() * BARRAGE_COLORS.length)]
}

/**
 * 生成唯一ID
 */
export function generateBarrageId(): string {
  return `barrage_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

/**
 * 创建弹幕对象
 */
export function createBarrage(
  text: string,
  options: Partial<Omit<BarrageItem, 'id' | 'text'>> = {}
): Omit<BarrageItem, 'id'> {
  return {
    text,
    color: getRandomColor(),
    type: 'scroll',
    fontSize: 20,
    time: 0,
    ...options
  }
}

/**
 * 验证弹幕数据
 */
export function validateBarrage(barrage: Partial<BarrageItem>): string[] {
  const errors: string[] = []

  if (!barrage.text || typeof barrage.text !== 'string') {
    errors.push('弹幕文本不能为空')
  }

  if (barrage.text && barrage.text.length > 100) {
    errors.push('弹幕文本长度不能超过100字符')
  }

  if (barrage.fontSize && (barrage.fontSize < 12 || barrage.fontSize > 48)) {
    errors.push('字体大小必须在12-48之间')
  }

  if (barrage.color && !isValidColor(barrage.color)) {
    errors.push('颜色格式不正确')
  }

  return errors
}

/**
 * 验证颜色格式
 */
export function isValidColor(color: string): boolean {
  const hexRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
  const rgbRegex = /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/
  const rgbaRegex = /^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/
  
  return hexRegex.test(color) || rgbRegex.test(color) || rgbaRegex.test(color)
}

/**
 * 计算文本宽度
 */
export function measureTextWidth(
  text: string, 
  fontSize: number = 20, 
  fontFamily: string = 'sans-serif'
): number {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) return text.length * fontSize * 0.6 // 估算值

  ctx.font = `bold ${fontSize}px ${fontFamily}`
  return ctx.measureText(text).width
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let lastCall = 0
  return (...args: Parameters<T>) => {
    const now = Date.now()
    if (now - lastCall >= delay) {
      lastCall = now
      func(...args)
    }
  }
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func(...args), delay)
  }
}

/**
 * 格式化时间
 */
export function formatTime(seconds: number): string {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

/**
 * 检查是否为移动设备
 */
export function isMobile(): boolean {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

/**
 * 获取设备像素比
 */
export function getDevicePixelRatio(): number {
  return window.devicePixelRatio || 1
}

/**
 * 弹幕文本过滤器
 */
export class BarrageFilter {
  private blockedWords: Set<string> = new Set()
  private blockedUsers: Set<string> = new Set()

  addBlockedWord(word: string): void {
    this.blockedWords.add(word.toLowerCase())
  }

  removeBlockedWord(word: string): void {
    this.blockedWords.delete(word.toLowerCase())
  }

  addBlockedUser(user: string): void {
    this.blockedUsers.add(user.toLowerCase())
  }

  removeBlockedUser(user: string): void {
    this.blockedUsers.delete(user.toLowerCase())
  }

  isBlocked(barrage: BarrageItem): boolean {
    // 检查用户
    if (barrage.user && this.blockedUsers.has(barrage.user.toLowerCase())) {
      return true
    }

    // 检查关键词
    const text = barrage.text.toLowerCase()
    for (const word of this.blockedWords) {
      if (text.includes(word)) {
        return true
      }
    }

    return false
  }

  filter(barrages: BarrageItem[]): BarrageItem[] {
    return barrages.filter(barrage => !this.isBlocked(barrage))
  }
}

/**
 * 弹幕统计工具
 */
export class BarrageStats {
  private totalCount = 0
  private blockedCount = 0
  private startTime = Date.now()

  addBarrage(): void {
    this.totalCount++
  }

  blockBarrage(): void {
    this.blockedCount++
  }

  getStats() {
    const runtime = (Date.now() - this.startTime) / 1000
    const rate = runtime > 0 ? this.totalCount / runtime : 0

    return {
      total: this.totalCount,
      blocked: this.blockedCount,
      passed: this.totalCount - this.blockedCount,
      blockRate: this.totalCount > 0 ? (this.blockedCount / this.totalCount) * 100 : 0,
      rate: rate,
      runtime: runtime
    }
  }

  reset(): void {
    this.totalCount = 0
    this.blockedCount = 0
    this.startTime = Date.now()
  }
}
